﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DotNetSpeech;

namespace FingerprintAttendance
{
    public partial class VerifyForm : Form
    {
        /// <summary>
        /// 指纹识别高速缓冲空间
        /// </summary>
        public  int fpcHandle = 0;//指纹识别高速缓冲空间
        int Score = 0;//比对最高分
        int ProcessNum = 0;//比对次数

        SpeechVoiceSpeakFlags SVSF = SpeechVoiceSpeakFlags.SVSFlagsAsync;
        SpVoice Speech = new SpVoice();

        public VerifyForm()
        {
            InitializeComponent();

        }

        private void VerifyForm_Load(object sender, EventArgs e)
        {

            this.WindowState = FormWindowState.Maximized;
            dgvVerifyInfo.AutoGenerateColumns = false;
            cbbUpload.SelectedIndex = 0;

            loadingCircle1.InnerCircleRadius = 59;
            loadingCircle1.OuterCircleRadius = 60;
            loadingCircle1.NumberSpoke = 30;
            loadingCircle1.SpokeThickness = 25;
            loadingCircle1.Active = true;
            plClock.Location = new Point((this.Width - plClock.Width) / 2, (this.Height - plClock.Height) / 2);

            
            //InitTemplate();

            panel31.Width = 26;

        }

        /// <summary>
        /// 添加指纹登记模板pRegTemplate到指纹识别高速缓冲空间fpcHandle，FPID是要添加登记模板的标识。
        /// </summary>
        private void InitTemplate()
        {
            DataTable dt = DataOperation.GetFingerprintSettings();
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["No"].ToString() == "Threshold")
                {
                    axZKFPEngX1.Threshold = int.Parse(dr["Value"].ToString());
                    break;
                }
            }

            if (axZKFPEngX1.InitEngine() != 0)
                MessageBox.Show("指纹采集仪初始化失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);


            //创建指纹识别高速缓冲空间，进行1：N识别时必须首先调用该函数得到指纹识别缓冲空间句柄。
            fpcHandle = axZKFPEngX1.CreateFPCacheDB();
            lbDeviceNum.Text = "设备序号:" + axZKFPEngX1.SensorSN;

            dt = DataOperation.GetFingerprint();

            foreach (DataRow dr in dt.Rows)
            {
                int FingerprintID = int.Parse(dr["FingerprintID"].ToString());
               
                object FRegTemplate = axZKFPEngX1.DecodeTemplate1((string)dr["Encode"]);
                //方法 AddRegTemplateToFPCacheDB(fpcHandle As Long, FPID As Long, pRegTemplate) As Long
                //添加指纹登记模板pRegTemplate到指纹识别高速缓冲空间fpcHandle，FPID是要添加登记模板的标识。
                axZKFPEngX1.AddRegTemplateToFPCacheDB(fpcHandle, FingerprintID, FRegTemplate);
            }


        }

        /// <summary>
        /// OnCapture(ActionResult AS Boolean, ATemplate)
        ///AutoIdentify = False时，取到用于比对的指纹验证模板ATemplate， ActionResult =true 表示成功取到指纹模版；False 表示失败。
        ///AutoIdentify =  True时，返回指纹比对结果(一维数组)，请参考下面定义： 

        ///ATemplate[0]  代表ID值 -1代表查找失败
        ///ATemplate[1]  返回1:N比对分数 即原来Identification函数中的Score参数
        ///ATemplate[2]  1:N指纹比对数
        ///ATemplate[3]  1:1指纹比对数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void axZKFPEngX1_OnCapture(object sender, AxZKFPEngXControl.IZKFPEngXEvents_OnCaptureEvent e)
        {
            bool success = false;
            //方法 IdentificationInFPCacheDB (fpcHandle As Long, pVerTemplate,  Byval Score As Long, Byval ProcessedFPNumber As Long) As Long
            //将指纹验证模板pVerTemplate和指纹识别高速缓冲空间fpcHandle中所有登记模板进行比对，Score传出ProcessedFPNumber次比对中的最高分数，ProcessedFPNumber传出比对的次数，当识别成功时返回值指纹标识，失败返回-1。
            //注意：
            //在识别过程中如果比对分数大于等于属性Threshold，则认为比对成功，不再和缓冲空间中剩余的指纹登记模板进行比对，函数返回匹配成功的指纹登记模板的指纹标识；
            //当指纹验证模板和指纹识别高速缓冲空间中所有指纹登记模板进行比对的分数都没有超过设定的Threshold，但同时比对的最高分数大于等于Score，则认为比对也是匹配成功，函数返回比对最高分数的指纹登记模板的标识，推荐设定为9；
            int result = axZKFPEngX1.IdentificationInFPCacheDB(fpcHandle, e.aTemplate, ref Score, ref ProcessNum);
            if (result == -1)
            {
                Speech.Speak("验证失败", SVSF);
                return;
            }


            DataTable dt = DataOperation.GetFingerprintById(result);

            try
            {
                #region 同一个用户在SpanMinutes分钟内进行多次考勤，只记录一次

                DataTable dt1 = DataOperation.GetMaxIdVerifyInfo(dt.Rows[0]["UserId"].ToString());
                int SpanMinutes = int.Parse(System.Configuration.ConfigurationSettings.AppSettings["SpanMinutes"]);

                if (dt1.Rows.Count > 0)
                {
                    System.TimeSpan ND = DateTime.Now - DateTime.Parse(dt1.Rows[0]["VerifyTime"].ToString());
                    if (ND.TotalMinutes <= SpanMinutes)
                    {
                        Speech.Speak(dt1.Rows[0]["UserName"].ToString() + "你已经登记了考勤！", SVSF);
                        return;
                    }

                }
                #endregion

                success = DataOperation.UploadVerifyInfo(dt.Rows[0]["UserType"].ToString(), dt.Rows[0]["UserId"].ToString(), DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
                if (!success)
                {
                    Speech.Speak("数据上传失败", SVSF);
                    //return;
                }
            }
            catch (Exception ex)
            {
                Speech.Speak("数据上传出错！", SVSF);
                //return;
            }

            try
            {
                DataOperation.AddVerifyInfo(dt.Rows[0]["UserId"].ToString(), dt.Rows[0]["UserName"].ToString(),
                                            dt.Rows[0]["UserType"].ToString(), dt.Rows[0]["UserNumber"].ToString(),
                                            DateTime.Now, success);

                dt = DataOperation.GetMaxIdVerifyInfo(dt.Rows[0]["UserId"].ToString());
                //dt = DataOperation.GetMaxIdVerifyInfo();
                if (dgvVerifyInfo.DataSource == null)
                {
                    dt.DefaultView.Sort = "VerifyTime desc";
                    dgvVerifyInfo.DataSource = new BindingSource(dt, null);
                }
                else
                {
                    ((DataTable)((BindingSource)dgvVerifyInfo.DataSource).DataSource).Merge(dt);
                }
                if (!success)
                    dgvVerifyInfo.Rows[0].DefaultCellStyle.BackColor = Color.Red;

                Speech.Speak(dt.Rows[0]["UserName"].ToString() + "欢迎光临", SVSF);

                txtUserNumber.Text = dt.Rows[0]["UserNumber"].ToString();
                txtUserName.Text = dt.Rows[0]["UserName"].ToString();
                txtVerifyTime.Text = DateTime.Now.ToString();
                if (dt.Rows[0]["UserType"].ToString() == "student")
                    cbbUserType.SelectedIndex = 1;
                else
                    cbbUserType.SelectedIndex = 2;
            }
            catch (Exception ex)
            {
                Speech.Speak("数据保存出错！", SVSF);
                return;
            }

        }

        public void axZKFPEngX1_OnFeatureInfo(object sender, AxZKFPEngXControl.IZKFPEngXEvents_OnFeatureInfoEvent e)
        {

            //aQuality(0-好的指纹,1-特征点不够,2-其它因导致不能取得指纹特征)
            if (e.aQuality != 0)
            {
                Speech.Speak("验证失败，请重新验证", SVSF);
            }

        }

        private void VerifyForm_Resize(object sender, EventArgs e)
        {
            plClock.Location = new Point((this.Width - plClock.Width) / 2, (this.Height - plClock.Height) / 2);
        }

        private void VerifyForm_Activated(object sender, EventArgs e)
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VerifyForm));
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));

            InitTemplate();
        }

        private void plShow_MouseClick(object sender, MouseEventArgs e)
        {
            plOperate.Visible = !plOperate.Visible;

            if (plOperate.Visible)
            {
                panel31.Width = 82;
                panel8.Visible = false;
                plShow.BackgroundImage = global::FingerprintAttendance.Properties.Resources.Show1;
            }
            else
            {
                panel31.Width = 26;
                panel8.Visible = true;
                plShow.BackgroundImage = global::FingerprintAttendance.Properties.Resources.Show2;
            }
        }

        private void tsbSearchVerifyInfo_Click(object sender, EventArgs e)
        {
            string upload = "", userType = "";
            if (cbbUpload.SelectedIndex == 1)
                upload = "True";
            else if (cbbUpload.SelectedIndex == 2)
                upload = "False";
            if (cbbUserType.SelectedIndex == 1)
                userType = "student";
            else if (cbbUserType.SelectedIndex == 2)
                userType = "staff";

            DataTable dt = DataOperation.GetVerifyInfo(txtUserName.Text, userType, txtUserNumber.Text, txtVerifyTime.Text, upload);
            dt.DefaultView.Sort = "VerifyTime desc";
            dgvVerifyInfo.DataSource = new BindingSource(dt, null);

            foreach (DataGridViewRow row in dgvVerifyInfo.Rows)
            {
                DataRow dr=CommonControl.GetRowInGridAt(dgvVerifyInfo,row.Index);
                if (!bool.Parse(dr["Upload"].ToString()))
                    row.DefaultCellStyle.BackColor = Color.Red;
            }
        }

        private void dtpVerifyTime_ValueChanged(object sender, EventArgs e)
        {
            txtVerifyTime.Text = dtpVerifyTime.Value.ToString("yyyy-MM-dd");
        }

        private void tsbDelVerifyInfo_Click(object sender, EventArgs e)
        {
           if (dgvVerifyInfo.DataSource == null||dgvVerifyInfo.SelectedRows.Count==0)
                return;
            if (MessageBox.Show("请确认删除选择的考勤信息！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
                return;
            try
            {
                ArrayList al = new ArrayList();
                foreach (DataGridViewRow dgvr in dgvVerifyInfo.Rows)
                {
                    if (!dgvr.Selected) continue;
                    DataRow dr = CommonControl.GetRowInGridAt(dgvVerifyInfo, dgvr.Index);

                    DataOperation.DelVerifyInfoById(int.Parse(dr["VerifyInfoId"].ToString()));

                    al.Add(dr);
                   
                }
                foreach (DataRow dr in al)
                    dr.Delete();
               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void tsbUploadVerifyInfo_Click(object sender, EventArgs e)
        {
            if (dgvVerifyInfo.DataSource == null || dgvVerifyInfo.SelectedRows.Count == 0)
                return;
            if (MessageBox.Show("请确认上传选择的考勤信息！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
                return;

            try
            {
                foreach (DataGridViewRow dgvr in dgvVerifyInfo.Rows)
                {
                    //if (!dgvr.Selected) continue;
                    DataRow dr = CommonControl.GetRowInGridAt(dgvVerifyInfo, dgvr.Index);
                    if (bool.Parse(dr["Upload"].ToString())) continue;

                    DataOperation.UploadVerifyInfo(dr["UserType"].ToString(), dr["UserId"].ToString(), dr["VerifyTime"].ToString());
                    DataOperation.UpdateVerifyInfoUpload(int.Parse(dr["VerifyInfoId"].ToString()), true);

                    dr["Upload"] = true.ToString();
                    dgvr.DefaultCellStyle.BackColor = Color.White;
                }

                MessageBox.Show("已经成功上传考勤数据！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void tsbClear_Click(object sender, EventArgs e)
        {
            txtUserNumber.Text = "";
            txtUserName.Text = "";
            txtVerifyTime.Text = "";
            cbbUserType.SelectedIndex = 0;
            cbbUpload.SelectedIndex = 0;
            dgvVerifyInfo.DataSource = null;
        }

        private void tsbManualVerify_Click(object sender, EventArgs e)
        {
            ManualVerifyForm mvf = new ManualVerifyForm();
            if (mvf.ShowDialog() == DialogResult.OK)
            {
                if (dgvVerifyInfo.DataSource == null)
                {
                    mvf.dt.DefaultView.Sort = "VerifyTime desc";
                    dgvVerifyInfo.DataSource = new BindingSource(mvf.dt, null);
                }
                else
                    ((DataTable)((BindingSource)dgvVerifyInfo.DataSource).DataSource).Merge(mvf.dt);

                if (!bool.Parse(mvf.dt.Rows[0]["Upload"].ToString()))
                    dgvVerifyInfo.Rows[0].DefaultCellStyle.BackColor = Color.Red;

                txtUserNumber.Text = mvf.dt.Rows[0]["UserNumber"].ToString();
                txtUserName.Text = mvf.dt.Rows[0]["UserName"].ToString();
                txtVerifyTime.Text = mvf.dt.Rows[0]["VerifyTime"].ToString();
                if (mvf.dt.Rows[0]["UserType"].ToString() == "student")
                    cbbUserType.SelectedIndex = 1;
                else
                    cbbUserType.SelectedIndex = 2;

            }
        }
     
    }
}
